var hotkeyCode;
var isCtrlShift;

chrome.extension.sendRequest({command: 'getHotkey'}, function(response) {
  if (!response)
    return;
		
  hotkeyCode = response.keycode;
  isCtrlShift = response.isCtrlShift;
	
  if (window == top)
    window.addEventListener("keyup", onKeyUp, false);
});

function onKeyUp(e) {
  if (!hotkeyCode)
  	return;
  
  var t = false;
  if (isCtrlShift && e.shiftKey || !isCtrlShift && !e.shiftKey)
  	t = true;
	
  if (e.ctrlKey && t && e.keyCode == hotkeyCode) {
	var str = window.getSelection().toString();
	var rect = window.getSelection().getRangeAt(0).getBoundingClientRect();
	
	if (str != "")
		chrome.extension.sendRequest({command: 'translate', text: str}, function(response){
			if (!response[0])
				return;
				
    		var html = response[1];
			
			var div = document.getElementById(containerId);
			
			if (!div) {
				div = document.createElement('div');
				div.id = containerId;
				div.className = 'mammoth-translation-result';
				
				div.addEventListener("keydown", function(e) {
					e.stopPropagation();
				}, false);
				
				div.addEventListener("mousedown", function(e) {
					e.stopPropagation();
				}, false);
			}
			
			div.innerHTML = html;
			document.body.appendChild(div);
			
			setLocation(div, rect);
			
			subscribe();
    	});
  }
}

function setLocation(div, rect){
	var body = document.body;
	
	var top;
	var left;
	var dx = 2;
	
	if (rect.top - div.offsetHeight > 0)
		top = rect.top - div.offsetHeight - dx;
	else
		top = rect.bottom + dx;
	
	if (rect.left + div.offsetWidth >= body.offsetWidth && rect.right - div.offsetWidth > 0)
		left = rect.right - div.offsetWidth;
	else
		left = rect.left;
	
	top += body.scrollTop;
	left += body.scrollLeft;
	
	div.style.top = top + 'px';
	div.style.left = left + 'px';
}

function subscribe() {
	window.addEventListener("keydown", hide, false);
	window.addEventListener("mousedown", hide, false);
	document.addEventListener("resize", hide, false);
}

function unSubscribe() {
	window.removeEventListener("keydown", hide, false);
	window.removeEventListener("mousedown", hide, false);
	document.removeEventListener("resize", hide, false);
}

function hide(e){
	if (e.keyCode != 0 && e.keyCode != 27)
		return;
	
	unSubscribe();
	
	var div = document.getElementById(containerId);
	
	if (div)
		document.body.removeChild(div);
}

var containerId = 'mammothTranslationResult';
